package com.example.demo.file;


import com.alibaba.fastjson.JSONObject;
import com.example.demo.entity.file;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

@CrossOrigin
@RestController
public class FileUploadController {

    /**
     * 实现文件上传
     */
    @RequestMapping(value = "/fileUpload", method = RequestMethod.POST)
    @ResponseBody
    public String fileUpload(MultipartFile file, HttpServletRequest request) throws IOException {

        String user = request.getParameter("mailbox");
        String url = request.getParameter("url");

        String path = "C:/manongyizhanFile/users/" + user + "/" + url;
        File dest = new File(path, file.getOriginalFilename());
        if (!dest.getParentFile().exists()) { //判断文件父目录是否存在
            dest.getParentFile().mkdir();
        }
        if (!dest.exists()) {
            dest.mkdirs();
        }
        try {
            file.transferTo(dest); //保存文件
            return "ok";
        } catch (IllegalStateException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            return "no";
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            return "no";
        }
    }

    //文件下载相关代码
    @RequestMapping(value = "/download", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
    public String downloadFile(@RequestBody JSONObject jsonObject, HttpServletRequest request, HttpServletResponse response) throws UnsupportedEncodingException {
//        String fileName = request.getParameter("filename");// 设置文件名，根据业务需要替换成要下载的文件名
        String fileName=jsonObject.getString("filename");
        if (fileName != null) {
            //设置文件路径
            String user = jsonObject.getString("mailbox");
            String realPath = "C:/manongyizhanFile/users/" + user + "/"+jsonObject.getString("url");
            File file = new File(realPath, fileName);
            if (file.exists()&&!file.isDirectory()) {
                response.setContentType("application/octet-stream");//
                response.setHeader("content-type", "application/octet-stream");
                response.setHeader("Content-Disposition", "attachment;filename=" + fileName + ";filename*=utf-8''" + URLEncoder.encode(fileName, "UTF-8"));

                byte[] buffer = new byte[1024];
                FileInputStream fis = null;
                BufferedInputStream bis = null;
                try {
                    fis = new FileInputStream(file);
                    bis = new BufferedInputStream(fis);
                    OutputStream os = response.getOutputStream();
                    int i = bis.read(buffer);
                    while (i != -1) {
                        os.write(buffer, 0, i);
                        i = bis.read(buffer);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    if (bis != null) {
                        try {
                            bis.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                    if (fis != null) {
                        try {
                            fis.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                }
                System.out.println(file);

            }
        }
        return null;
    }

    //遍历文件夹文件
    @ResponseBody
    @RequestMapping(value = "/selectfileList", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
    public String selectfileList(@RequestBody JSONObject jsonObject) throws FileNotFoundException, IOException {
        String filepath = "C:\\manongyizhanFile\\users\\" + jsonObject.get("mailbox") + "\\" + jsonObject.get("url");

        File file = new File(filepath);
        List<file> list = new ArrayList<>();
        if (file.isDirectory()) {
            String[] filelist = file.list();
            for (int i = 0; i < filelist.length; i++) {
                File readfile = new File(filepath + "\\" + filelist[i]);
                if (!readfile.isDirectory()) {
                    getCreateTime(readfile);
                    file f = new file();
                    if (readfile.length() < 1048576) {
                        BigDecimal bg = new BigDecimal(readfile.length() / 1024.0);
                        f.setMemory(bg.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue() + "K");
                    } else {
                        BigDecimal bg = new BigDecimal(readfile.length() / 1024.0 / 1024.0);
                        f.setMemory(bg.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue() + "M");
                    }
                    f.setName(readfile.getName());
                    f.setTime(getCreateTime(readfile));
                    f.setType(readfile.getName().substring(readfile.getName().lastIndexOf(".") + 1));
                    f.setSrc(filelogo(f.getType()));
                    list.add(f);
                } else {
                    file f = new file();
                    f.setType("wjj");
                    f.setName(readfile.getName());
                    f.setTime(getCreateTime(readfile));
                    if (getFileSize(readfile) < 1048576) {
                        BigDecimal bg = new BigDecimal(getFileSize(readfile) / 1024.0);
                        f.setMemory(bg.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue() + "K");
                    } else {
                        BigDecimal bg = new BigDecimal(getFileSize(readfile) / 1024.0 / 1024.0);
                        f.setMemory(bg.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue() + "M");
                    }
                    f.setSrc(filelogo(f.getType()));
                    list.add(f);
                }
            }
        }


        List<file> alist = new ArrayList();
        for (int i = 0;i<list.size();i++){
            if (list.get(i).getType().equals("wjj")){
                alist.add(list.get(i));
            }
        }
        for (int i = 0;i<list.size();i++){
            if (!list.get(i).getType().equals("wjj")){
                alist.add(list.get(i));
            }
        }
        return alist.toString();
    }

    //取得文件夹大小
    public long getFileSize(File f) {
        long size = 0;
        File flist[] = f.listFiles();
        for (int i = 0; i < flist.length; i++) {
            if (flist[i].isDirectory()) {
                size = size + getFileSize(flist[i]);
            } else {
                size = size + flist[i].length();
            }
        }
        return size;
    }

    //文件logo
    public String filelogo(String type) {
        String string[] = {
                "apk", "docx", "exe", "java", "jpg", "mp3",
                "mp4", "pdf", "png", "ppt", "rar", "txt", "xls", "zip", "wjj"
        };
        for (int i = 0; i < string.length; i++) {
            if (type.equals(string[i])) {
                return type;
            }
        }
        return "default";
    }

    //获取文件的修改时间
    public String getCreateTime(File f) {
        Calendar cal = Calendar.getInstance();
        long time = f.lastModified();
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        cal.setTimeInMillis(time);
        return formatter.format(cal.getTime());
    }

    //删除文件夹和文件
    @PostMapping(value = "/delete", produces = "application/json;charset=UTF-8")
    public void delete(@RequestBody JSONObject jsonObject) {
        String filepath = "C:/manongyizhanFile/users/" + jsonObject.getString("mailbox") + "/"+jsonObject.getString("url");
        File file = new File(filepath);
        if (!file.isDirectory()) {
            file.delete();
        } else {
            deleteDir(file);
        }
    }

    @PostMapping (value = "/newfolder", produces = "application/json;charset=UTF-8")
    public String newfolder(@RequestBody JSONObject jsonObject){
        String filepath = "C:/manongyizhanFile/users/" + jsonObject.getString("mailbox") + "/"+jsonObject.getString("url");
        System.out.println(filepath);
        File file=new File(filepath);
        if(!file.exists()){//如果文件夹不存在
            file.mkdir();//创建文件夹
        }
        return jsonObject.toString();
    }

    //递归操作删除
    private boolean deleteDir(File dir) {
        if (dir.isDirectory()) {
            String[] children = dir.list();
            //递归删除目录中的子目录下
            for (int i = 0; i < children.length; i++) {
                boolean success = deleteDir(new File(dir, children[i]));
                if (!success) {
                    return false;
                }
            }
        }
        // 目录此时为空，可以删除
        return dir.delete();
    }
}
